package com.seari.controller;

import com.seari.influxdb.InfluxDBConnection;
//import com.seari.influxdb.InfluxDBUtil;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping(value = "/influxdb")
public class InfluxDBController {

    @Autowired
    InfluxDBConnection influxDBConnection;


    @RequestMapping(value = "/get")
    @ResponseBody
    public Object getInfluxDB(HttpServletRequest request) throws Exception {

        String databases = request.getParameter("databases");
        String table = request.getParameter("table");
        String retentionPolicy = request.getParameter("retentionPolicy");
        List<Object> datas = new ArrayList<>();
        QueryResult query = influxDBConnection.query("SELECT * FROM "+databases+"."+retentionPolicy+"."+table+" ");
        datas.addAll(query.getResults());
        return datas;
    }
    @RequestMapping(value = "/add")
    @ResponseBody
    public void add(HttpServletRequest request) throws Exception {
        Map<String, String> tags = new HashMap<String, String>();
        Map<String, Object> fields = new HashMap<String, Object>();
        Enumeration<String> names = request.getParameterNames();

        String key = "";
        String value = "";
        while (names.hasMoreElements()) {
            key = names.nextElement();
            value = request.getParameter(key).trim();
            if (key.contains("TAG_")){
                tags.put(key, value);
            }else {
                fields.put(key, value);
            }
        }
        influxDBConnection.insert("meatablea502",tags, fields, System.currentTimeMillis(), TimeUnit.NANOSECONDS);
    }
}
